import { CurrentUser, RealIp } from '@/decorators';
import { MarketListDto, MarketOrderDto, MarketSalesDto } from '@/dtos';
import { MarketService } from '@/services/market.service';
import { halt, ok } from '@/utils';
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { Throttle, seconds } from '@nestjs/throttler';
import { BaseController } from './base.controller';

@Controller('market')
export class MarketController extends BaseController {
  constructor(private readonly marketService: MarketService) {
    super();
  }

  @Post('order')
  @Throttle({
    short: {
      ttl: seconds(1),
      limit: 5,
    },
  })
  async order(
    @Body() dto: MarketOrderDto,
    @CurrentUser('id') userId: number,
    @RealIp() ip: string,
  ) {
    if (await this.redis.get(`market:limit:${userId}`)) {
      return halt(`批量下单取消后, 限制下单5分钟`);
    }
    if (await this.redis.get(`order:limit:${userId}`)) {
      return halt(`连续3次下单取消后, 限制下单3分钟`);
    }
    return ok(await this.marketService.order(dto, userId, ip));
  }

  @Post('list')
  async getList(@Body() dto: MarketListDto, @CurrentUser('id') userId: number) {
    return ok(await this.marketService.getList(userId, dto));
  }

  @Post('sales')
  async getSales(@Body() dto: MarketSalesDto) {
    return ok(await this.marketService.getSales(dto));
  }

  @Post('admin/sales')
  async adminSales(@Body() dto: MarketSalesDto) {
    return ok(await this.marketService.adminSales(dto));
  }

  @Get('record/:assetId')
  async getRecord(@Param('assetId') assetId: number) {
    return ok(await this.marketService.getRecord(assetId));
  }

  @Get('admin/check/status')
  async status() {
    const queueCache = await this.redis.exists('bull:market:repeat');
    if (!queueCache) {
      return ok(0);
    } else {
      return ok(1);
    }
  }

  @Get('admin/check/switch')
  async witch() {
    const queueCache = await this.redis.exists('bull:market:repeat');
    if (!queueCache) {
      await this.marketService.start();
      return ok(1);
    } else {
      await this.marketService.close();
      return ok(0);
    }
  }
}
